import axios from 'axios'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'

const service = axios.create({
  // baseURL: 'http://47.98.138.183:8081',
  baseURL: 'http://127.0.0.1:8082/',
  timeout: 5000
})

// 请求拦截
service.interceptors.request.use(
  config => {
    // console.log('/utils/request:config', config)
    // 让每个请求都携带token
    config.headers['X-Token'] = getToken()
    return config
  },
  error => {
    // console.log('util/request/请求拦截err:', error)
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  response => {
    const res = response.data
    // code不等于200,显示错误
    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 3000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // console.log('util/request/响应拦截data', res)
      return res
    }
  },
  error => {
    // console.log('util/request/响应拦截err:', error)
    return Promise.reject(error)
  }
)

export default service
